<?php
/**
 * Created by PhpStorm .
 * User: 杜磊磊
 * Date: 2020/6/24
 * Time: 10:21
 */

namespace app\api\middleware;

class Auth
{
    public function handle($request, \Closure $next)
    {
        if(in_array($request->pathinfo(),config("userlogin.need_login"))){
            if (!$this->isLogin()){
                return show(config('status.not_login'),'用户没有登录');
            }
            $accessToken = request()->header("access-token");
            $userInfo = cache(config("redis.token_pre").$accessToken);
            $request->userId = $userInfo["id"];
            $request->asscessToken = $accessToken;
            $request->username = $userInfo["username"];
        }
        return $next($request);
    }

    /**
     * 判断用户是否登录
     * @return bool
     */
    public function isLogin()
    {
        $accessToken = request()->header("access-token");
        if ($accessToken){
            $userInfo = cache(config("redis.token_pre").$accessToken);
            if (!empty($userInfo['id'] && !empty($userInfo['username']))){
                return true;
            }
        }
        return false;
    }
}